/*
 * Copyright 2012 yura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opu.pc.ui.client.authentication;

import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.*;
import org.opu.pc.security.PreAuthenticatedAuthenticationToken;
import org.opu.pc.security.UserDetailsData;
import org.opu.pc.ui.client.actions.AbstractAction;
import org.opu.pc.ui.client.i18n.AbstractI18N;
import org.opu.pc.ui.client.widgets.PropertiesEditPane;
import org.opu.pc.ui.util.GUIUtils;
import org.opu.pc.ui.util.ImagePanel;
import org.opu.pc.ui.util.Logger;
import org.opu.pc.ui.util.Options;
import org.opu.pc.ui.util.ResourceHandle;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

/**
 *
 * @author yura
 */
public class AuthenticationDialog extends JDialog {
    
    private static final Logger logger = Logger.create(AuthenticationSystem.class);
    private static final AbstractI18N i18n = new AbstractI18N(
            "org.opu.pc.ui.resource.AuthenticationI18N");

    private ProviderManager providerManager;
    private boolean guestAvailable;
    
    public AuthenticationDialog(final ProviderManager providerManager,
            boolean guestAvailable) {

        super((JFrame)null, ResourceHandle.getApplicationTitle(), true);
        
        this.providerManager = providerManager;
        this.guestAvailable = guestAvailable;
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        
		LinkedHashMap<String, Object> properties = new LinkedHashMap<String, Object>();
		properties.put("user.name", System.getProperty("user.name"));
		properties.put("user.password", "");

        PropertiesEditPane pane = new PropertiesEditPane(properties, i18n, new HashMap());
        final AbstractAction cancelAction = new OkAction(pane){
            @Override public void runAction(ActionEvent e) throws Exception {
                System.exit(1);
            }

            @Override public String getName() {
                return "Cancel";
            }
        };

        addWindowListener(new WindowAdapter() {
			@Override public void windowClosing(WindowEvent e) {
				cancelAction.actionPerformed(null);
			}
		});

//		JPanel cp = new JPanel(new BorderLayout());
        ImagePanel cp = new ImagePanel(ResourceHandle.getImage("bg_4.png",
                ResourceHandle.IconType.large));
		cp.add(pane.getComponent(0));
		
		Box b = Box.createHorizontalBox();
		b.add(new JButton(cancelAction));
        if (guestAvailable){
            b.add(Box.createHorizontalStrut(GUIUtils.DEFAULT_SPACE));
            b.add(new JButton(new OkAction(pane){
                @Override public void runAction(ActionEvent e) throws Exception {
                    UserDetailsData.setAuthentication(providerManager.authenticate(
                        new PreAuthenticatedAuthenticationToken("GuestAuthentication", null)));
                    hideDialog();
                }

                @Override public String getName() {
                    return "GuestCredentials";
                }
            }));
        }
		b.add(Box.createHorizontalStrut(GUIUtils.DEFAULT_SPACE));
		b.add(new JButton(new OkAction(pane)));
		cp.add(GUIUtils.vBorder(GUIUtils.hCenter(b)), BorderLayout.SOUTH);

		getContentPane().add(cp);

		pack();
		setSize(400, getSize().height);
		setLocationRelativeTo(null);
//        setVisible(true);
    }
    
    
    class OkAction extends AbstractAction {
		protected final PropertiesEditPane pane;

		public OkAction(PropertiesEditPane pane) {
            super(true);
			this.pane = pane;
            putValue(LARGE_ICON_KEY, ResourceHandle.getIcon(getIconName(),
                    ResourceHandle.IconType.small));
		}

		@Override
		public String getName() {
			return "Ok";
		}

        public void hideDialog(){
            dispose();
        }

		@Override
		public void runAction(ActionEvent e) throws Exception {
            Map<String, Object> prop = pane.getProperties();
            try {
                UserDetailsData.setAuthentication(providerManager.authenticate(
                        new UsernamePasswordAuthenticationToken(
                            prop.get("user.name"),
                            prop.get("user.password"))));
                hideDialog();
            } catch (Exception ex) {
                logger.warning(ex);
                Options.error(ex);
            }
        }
	}
    
}
